package com.ruoyi.web.controller.cpsp;
/*
    @author neu.xiangwenjuan
    @create 2023/3/14
*/

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.cpsp.domain.*;
import com.ruoyi.cpsp.mapper.CurrentPerformanceDataMapper;
import com.ruoyi.cpsp.mapper.DepartmentMapper;
import com.ruoyi.cpsp.mapper.TeamGroupMapper;
import com.ruoyi.cpsp.service.CurrentPerformanceDataService;
import com.ruoyi.cpsp.service.DepartmentService;
import com.ruoyi.cpsp.service.EmployeeService;
import com.ruoyi.cpsp.service.EvaluateRecordDetailService;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/cpsp/current")
public class CurrentPerformanceDataController {

    @Autowired
    private CurrentPerformanceDataService currentPerformanceDataService;

    @Autowired
    private CurrentPerformanceDataMapper currentPerformanceDataMapper;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private TeamGroupMapper teamGroupMapper;

    @Autowired
    private EvaluateRecordDetailService detailService;
//
//    private EmployeeController employeeController = new EmployeeController();
    // 添加数据，初始表的内容。每季度开始时自动 见tool/TimingTaskImpl.java updateCurrentPerformanceData

    // 更新表中数据，当有人违章时更新表中信息 见EvaluateRecordDetailServiceImpl.java/updateCurrentPerformanceData

    // 查询数据表内容，返回到前端显示。
    /**
     * 分页显示，一次几条数据。
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation("获得当前季度人员绩效信息")
    @RequestMapping(value = "/getCurrentPerformanceData", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getCurrentPerformanceData(@RequestParam(defaultValue = "1") Integer pageNum,
                                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        List<String> idCardList = employeeService.selectCardByDepart(dept.getDeptName(), 0);

        PageHelper.startPage(pageNum,pageSize);
        List<CurrentPerformanceDataEn> currentPerformanceDataEns = new ArrayList<>();
        if (role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) {
            currentPerformanceDataEns = currentPerformanceDataService.selectAll();
        }else if (role.equals("department")){
            currentPerformanceDataEns = currentPerformanceDataService.selectDataByIdCard(idCardList);

        }
        PageInfo pageInfo = PageInfo.of(currentPerformanceDataEns);

        return AjaxResult.success(pageInfo);
    }



    @ApiOperation("获得当前绩效总值")
    @RequestMapping(value = "/getYearAndQuarter", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getYearAndQuarter() {
        return AjaxResult.success(currentPerformanceDataMapper.selectYear());
    }
    /**
     *  平时不需要筛选的时候把departmentId设置为""
     */
    @ApiOperation("获得当前绩效总值")
    @RequestMapping(value = "/getCurrentPerformanceSum", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getCurrentPerformanceSum(@RequestParam(required = false) String departmentId,
                                                @RequestParam(required = false) Integer year,
                                                @RequestParam(required = false) Integer quarter,
                                                @RequestParam(required = false) Integer tempGroupId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        double sum = 0.0;
        if ((role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) && (departmentId == null || departmentId.equals(""))) {
            sum = currentPerformanceDataService.selectSum(year, quarter);
        }else if((role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) && departmentId.length() > 0) {
            List<String> idCards = employeeService.selectCardByDepart(departmentId, tempGroupId);
            sum = idCards.size() == 0 ? 0 : currentPerformanceDataService.selectSumDepart(idCards, year, quarter);
        }else if (role.equals("department")){
            List<String> idCardList = employeeService.selectCardByDepart(dept.getDepartmentId(), tempGroupId);
            sum = idCardList.size() == 0 ? 0 : currentPerformanceDataService.selectSumDepart(idCardList, year, quarter);
        }
        return AjaxResult.success(sum);
    }


    /**
     * 筛选条件：班组，姓名，身份证号。部门登录，只能查看本部门的信息。
     * @param pageNum
     * @param pageSize
     * @param department 管理员登陆时，根据部门筛选
     * @param teamGroup 根据班组筛选
     * @param employeeInfo 根据员工姓名或者身份证号
     * @return
     */
    @ApiOperation("筛选获得当前季度人员绩效信息")
    @RequestMapping(value = "/getCurrentPerformanceDataSelect", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getCurrentPerformanceDataSelect(@RequestParam(defaultValue = "1") Integer pageNum,
                                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                                       @RequestParam(required = false) String department,
                                                       @RequestParam(required = false) Integer teamGroup,
                                                       @RequestParam(required = false) String employeeInfo){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        String departmentId = dept.getDepartmentId();

        PageInfo<CurrentPerformanceDataEn> source = new PageInfo<>();

        String departId = department == null ? "" : department;
        Integer teamId = teamGroup == null ? 0 : teamGroup;
        String employeeIn = employeeInfo == null ? "" : employeeInfo;

        List<CurrentPerformanceDataEn> currentPerformanceDataEns = new ArrayList<>();
        if (role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) {
            source = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {
                currentPerformanceDataService.selectSelective(departId, teamId, employeeIn);
            });
            currentPerformanceDataEns = new ArrayList<>(source.getList());
        }else if (role.equals("department")) {
            source = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {
                currentPerformanceDataService.selectSelective(departmentId, teamId, employeeIn);
            });
            currentPerformanceDataEns = new ArrayList<>(source.getList());
        }
        PageInfo<CurrentPerformanceDataEn> target = new PageInfo<>();
        BeanUtils.copyProperties(source, target);
        target.setList(currentPerformanceDataEns);
        // TODO
//        currentPerformanceDataService.insertPerformance();
        return AjaxResult.success(target);
    }

    /**
     *
     * 需要判断登录人为部门领带还是其他，部门领导只能导出本部门数据，其他人可以导出所有数据。
     * 导出当前季度数据，查询currentPerformanceData表，否则查询previousPerformanceData
     * @return
     */
    @ApiOperation("导出当前季度绩效信息")
    @RequestMapping(value = "/loadPerformanceInfo", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult loadPerformanceInfo() {
        // 获取登录人的身份和个人信息。
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        String departmentId = dept.getDepartmentId();

        ArrayList<EvaluateRecordDepart> result = new ArrayList();
        List<Department> departments = departmentService.selectAll();
        if (role.equals("department")) {
            Department department = departmentMapper.selectByDepartmentId(departmentId);
            EvaluateRecordDepart depart = getPerformanceByDepart(departmentId, department.getDepartmentName());
            result.add(depart);
        }else if(role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) {
            EvaluateRecordDepart depart = new EvaluateRecordDepart();
            for (Department department:departments) {
                depart = getPerformanceByDepart(department.getDepartmentId(), department.getDepartmentName());
                result.add(depart);
            }
        }
        return AjaxResult.success(result);
    }

    private EvaluateRecordDepart getPerformanceByDepart(String departmentId, String departmentName) {
        List<CurrentPerformanceDataEn> dataEnList = currentPerformanceDataService.selectSelective(departmentId, null, null);
        EvaluateRecordTeam team = new EvaluateRecordTeam();
        team.setTeamGroupName("总表");
        team.setDataList(dataEnList);
        team.setTotal(currentPerformanceDataService.selectDataTotal(departmentId, null));
        ArrayList<EvaluateRecordTeam> teams = new ArrayList<>();
        teams.add(team);

        List<TeamGroup> teamGroupList = teamGroupMapper.findTeamGroupByDepart(departmentId);
        for (TeamGroup teamGroup: teamGroupList) {
            List<CurrentPerformanceDataEn> teamList = currentPerformanceDataService.selectSelective(departmentId, teamGroup.getId(), null);
            CurrentPerformanceTotal teamTotal = currentPerformanceDataService.selectDataTotal(departmentId, teamGroup.getId());
            EvaluateRecordTeam team1 = new EvaluateRecordTeam();
            team1.setDataList(teamList);
            team1.setTeamGroupName(teamGroup.getTeamGroupName());
            team1.setTotal(teamTotal);
            teams.add(team1);
        }
        EvaluateRecordDepart depart = new EvaluateRecordDepart();
        depart.setDepartmentName(departmentName);
        depart.setDepartList(teams);
        return depart;
    }// departmentlist{departmentName:"" ;departDataList:Arraylist<>{name:"总表"，list<>,total绩效数}，{各个部门名字，list，total}}


    /**
     *
     * @param
     * id:id，唯一标识；cumulativeBase：绩效初值；propOfPunishment：扣减比例；onWork：在岗天数
     * @return
     */
    @ApiOperation("更新绩效数据")
    @RequestMapping(value = "/updateCurrentPerformance", method = RequestMethod.POST)
    @ResponseBody
    private AjaxResult updateCurrentPerformance(@RequestParam Integer id,
                                                @RequestParam Integer year,
                                                @RequestParam Integer quarter,
                                                @RequestParam String employee_idCard,
                                                @RequestParam(required = false) double cumulativeBase,
                                                @RequestParam(required = false) double propOfPunishment,
                                                @RequestParam(required = false) Integer onWork,
                                                @RequestParam(required = false) String annotation) {
        // 根据id从数据库中获取数据
        CurrentPerformanceData currentPerformanceData = currentPerformanceDataMapper.selectById(id);
        currentPerformanceData.setCumulativeBase(cumulativeBase);
        currentPerformanceData.setProportionOfPunishment(propOfPunishment);
        try {
            if (onWork < 45 || (detailService.selectDetailByEmployeeYear(employee_idCard, year, quarter).size() >= 1)){
                currentPerformanceData.setIncreaseBase(0.0);
            }else {
                boolean isDirect = employeeService.getIsDirectProducer(employee_idCard);
                if (isDirect) {
                    if ((cumulativeBase + 100.0) > 1000) {
                        currentPerformanceData.setIncreaseBase(1000 - cumulativeBase);
                    }else {
                        currentPerformanceData.setIncreaseBase(100.0);
                    }
                }else {
                    if ((cumulativeBase + 50.0) > 500) {
                        currentPerformanceData.setIncreaseBase(500 - cumulativeBase);
                    }else {
                        currentPerformanceData.setIncreaseBase(50.0);
                    }
                }
            }
            currentPerformanceData.setValueOfPunishment((cumulativeBase + currentPerformanceData.getIncreaseBase())* propOfPunishment);
            currentPerformanceData.setCurrentBase(cumulativeBase + currentPerformanceData.getIncreaseBase() - currentPerformanceData.getValueOfPunishment());
            currentPerformanceData.setMoneyEveryMonth(currentPerformanceData.getCurrentBase());
            currentPerformanceData.setMoneyQuarter(3 * currentPerformanceData.getMoneyEveryMonth());
            currentPerformanceData.setOnWork(onWork);
            currentPerformanceData.setAnnotation(annotation);
            int tag = currentPerformanceDataService.updateByPrimaryKeySelective(currentPerformanceData);
            if (tag > 0) {
                return AjaxResult.success("更新成功！");
            }else {
                return AjaxResult.error("更新失败！");
            }
        }catch (NumberFormatException e) {
            return AjaxResult.error("请输入在岗天数");
        }
    }

    @ApiOperation("获取季度中违章人员的身份证号列表")
    @RequestMapping(value = "/getEvaluateCardList", method = RequestMethod.POST)
    @ResponseBody
    private AjaxResult getEvaluateCardList(@RequestParam Integer year,
                                           @RequestParam Integer quarter) {
        List<String> idCards = detailService.getEvaluateCardList(year, quarter);
        return AjaxResult.success(idCards);
    }

}
